// cookie_test.ts - 测试cookie设置和验证
import { setAdminSessionCookie, checkIsAdmin } from "./auth.ts";

// 模拟请求和响应
class MockHeaders extends Headers {
  cookies: Record<string, string> = {};

  constructor(init?: HeadersInit) {
    super(init);
  }
  
  override set(name: string, value: string): void {
    if (name.toLowerCase() === 'set-cookie') {
      // 提取cookie名称和值
      const match = value.match(/^([^=]+)=([^;]+)/);
      if (match) {
        const [, cookieName, cookieValue] = match;
        this.cookies[cookieName] = cookieValue;
        console.log(`设置cookie: ${cookieName}=${cookieValue.substring(0, 20)}...`);
      }
    }
    super.set(name, value);
  }
}

// 创建一个模拟请求对象，包含cookie
function createMockRequestWithCookie(cookieName: string, cookieValue: string): Request {
  const headers = new Headers();
  headers.set('cookie', `${cookieName}=${cookieValue}`);
  
  return new Request('http://localhost:8000/', {
    headers: headers
  });
}

async function testCookieFunctions() {
  console.log("====== Cookie 功能测试 ======");
  
  // 1. 测试设置cookie
  console.log("\n1. 测试设置管理员会话cookie...");
  const headers = new MockHeaders();
  
  await setAdminSessionCookie(
    headers,
    1,              // userId
    "admin",        // username
    "管理员",       // displayName
    null            // avatarUrl
  );
  
  // 获取设置的cookie值
  const cookieHeader = headers.get('set-cookie');
  console.log("Set-Cookie头:", cookieHeader);
  
  if (!cookieHeader) {
    console.error("❌ 失败: 未能设置cookie");
    return;
  }

  // 解析出cookie值
  const match = cookieHeader.match(/^admin_session_token_v3=([^;]+)/);
  if (!match) {
    console.error("❌ 失败: 无法解析cookie值");
    return;
  }
  
  const cookieValue = match[1];
  console.log("Cookie值 (部分):", cookieValue.substring(0, 30) + "...");
  
  // 2. 测试验证cookie
  console.log("\n2. 测试验证含有管理员cookie的请求...");
  const mockRequest = createMockRequestWithCookie("admin_session_token_v3", cookieValue);
  
  // 定义一个模拟的ctx对象
  const mockCtx = {
    state: {}
  };
  
  // 调用验证函数
  const isAdmin = await checkIsAdmin(mockRequest, mockCtx as any);
  
  console.log("检查结果 isAdmin:", isAdmin);
  console.log("ctx.state:", mockCtx.state);
  
  if (isAdmin) {
    console.log("✅ 成功: 验证通过，用户被识别为管理员");
  } else {
    console.error("❌ 失败: 验证失败，用户未被识别为管理员");
  }
}

// 运行测试
if (import.meta.main) {
  await testCookieFunctions();
} 